/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.project.engineering;

import com.google.common.base.Strings;
import java.io.File;
import java.security.CodeSource;
import javax.naming.ConfigurationException;
import org.apache.log4j.Level;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;

/**
 *
 * @author ksmolnicki
 */
public class App {

  public static void main(String[] args) throws Exception {

    if (Strings.isNullOrEmpty(System.getProperty("port.name"))) {
      System.err.println("You have to provide serial port name: -Dport.name=\"port name\"");
      throw new ConfigurationException("Serial port name does not specified.");
    }

    CodeSource codeSource = App.class.getProtectionDomain().getCodeSource();
    File jarFile = new File(codeSource.getLocation().toURI().getPath());
    String jarDir = jarFile.getParentFile().getPath();

    System.setProperty("application.jar.dir", jarDir);
    System.setProperty("java.library.path", jarDir + File.separator + "lib" + File.separator + "linux");

    Server server;
    String portNumber = System.getProperty("server.port.number");
    
    if (!Strings.isNullOrEmpty(portNumber)) {
      try {
        server = new Server(Integer.parseInt(portNumber));
      } catch (NumberFormatException e) {
        throw new ConfigurationException("Invalid port number");
      }
    } else {
      server = new Server(8080);
    }

    org.apache.log4j.LogManager.getLogger("org.eclipse.jetty").setLevel(Level.WARN);

    WebAppContext root = new WebAppContext();
    root.setContextPath("/");
    root.setWar(App.class.getProtectionDomain().getCodeSource().getLocation().getPath());


    server.setHandler(root);

    server.start();
    server.join();
  }
}
